今天來解YKL08(UVA100):The 3n + 1 problem


找出介於i和j之間的數
所產生的數列中最大的cycle length
在敘述中已經把演算法列出來了
只需要將計算出序列的number的總和即可
#include <bits/stdc++.h>
using namespace std;
int alg(int n){
	int count = 0;
	while(n != 1){
		if(n % 2 == 1){
			n = 3 * n + 1;
		}else{
			n = n / 2;
		}
		count++;
	}
	count++;
	return count;
}
int main(){
	int i,j;
	
	while(cin >> i >> j){
		vector<int> arr;
		cout << i << " " << j ;
		if(i > j){
			int tmp;
			tmp = j;
			j = i;
			i = tmp;
		}
		
		for(i ;i <= j;i++){
			arr.push_back(alg(i));
		}
		cout << " " << *max_element(arr.begin(),arr.end()) << endl;
	}
	return 0;
}